<?php

class MemberAction extends CommonAction{

	// 检查帐号
	public function checkAccount() {
        if(!preg_match('/^[a-z]\w{3,}$/i',$_POST['account'])) {
            $this->error( '用户名必须是字母,且4位以上,建议使用会员姓名拼音!');
        }
		$User = M("Member");
        // 检测用户名是否冲突
        $name  =  $_REQUEST['account'];
        $result  =  $User->getByAccount($name);
        if($result) {
        	$this->error('该用户名已经存在！');
        }else {
           	$this->success('该用户名可以使用！');
        }
    }

	// 检查卡号
	public function checkCardNumber(){
		if(!preg_match('/^[0-9]\d{5,}$/i',$_REQUEST['number'])) {
            $this->error( '卡号必须是数字,且6位以上！');
        }
		$number =  $_REQUEST['number'];

		$Card   = M('Card');
		$result = $Card->where('cardNumber='.$number)->find();
		if($result){
			$this->error('该卡已存在!');
		}else{
			$this->success('该卡号可以使用!'.$result);
		}
	}
	// 检查卡号
	public function checkCardSerial(){
		if(!preg_match('/^[0-9]\d{3,}$/i',$_REQUEST['serial'])) {
            $this->error( '序列号必须是数字!');
        }
		$serial =  $_REQUEST['serial'];

		$Card   = M('Card');
		$result = $Card->where('cardSerial='.$serial)->find();
		if($result){
			$this->error('该卡已存在!');
		}else{
			$this->success('该卡号可以使用!'.$result);
		}
	}

	// 获取卡类型销售金额
	public function getCardTypeMoney(){
		$typeId  =  $_REQUEST['typeId'];
		$Card_type = M('Cardtype');
		$card_type = $Card_type->getById($typeId);
		if($card_type){
			$this->ajaxReturn($card_type,"获取成功",1);
		}else{
			$this->ajaxReturn(0,"获取失败",1);
		}
	}


	//前置操作
    function _before_add(){
		$Card_type        = M('Cardtype');	// 会员卡类型
		$card_type_list   = $Card_type->where('status=1')->select();
		$this             ->assign("card_type_list",$card_type_list);
		$Role             = M('Role');
		$role_sale        = $Role ->getByName('销售顾问');
		$role_id          = $role_sale[id];
		$Saler            = M('User');
		$salers           = $Saler
				          ->join('dudu_role_user on id= dudu_role_user.user_id')
				          ->where("dudu_role_user.role_id=$role_id")
				          ->select();
		if($_REQUEST['cardSerial']){
			$this->assign("cardSerial",$_REQUEST['cardSerial']);
		}
		$this->assign("salers",$salers);
    }

	function insert(){
		$Member = D('Member');
		if (false === $Member->create ()) {
			$this->error ( $Member->getError () );
		}
		$Member->startTrans();  //启用事务
		//保存当前数据对象
		$list=$Member->add ();
		if ($list!==false) { //保存成功
			// 添加一张会员卡
			$Card = M('Card');
			$data['memberId']       = $list ;
			$data['cardTypeId']     = $_REQUEST['cardTypeId'];
			$data['cardSerial']     = $_REQUEST['cardSerial'];
			$data['cardNumber']     = $_REQUEST['cardNumber'];
			$data['money']          = $_REQUEST['payMoney'];
			$data['salerId']        = $_REQUEST['salerId'];

			$User                   = M("User");  //获取销售顾问名
			$user                   = $User->getById($_REQUEST['salerId']);

			$data['salerName']      = $user['nickname'];
			$data['startDate']      = date('Y-m-d',time());
			$Cardtype               = M('Cardtype');
			$cardtype               = $Cardtype->getById($_REQUEST['cardTypeId']);
			$data['typeName']       = $cardtype['name'];
			$months                 = $cardtype['months'];
			$data['extMoney']       = $cardtype['extMoney'];
			$data['endDate']        = date('Y-m-d',strtotime("+ $months month"));
			$cardId = $Card->add($data);
			if($cardId){ //更新会员信息
				$memberData['cardId']  =  $cardId;
				$result = $Member->where("id=$list")->save($memberData);
				if($result){ //添加消费记录
					$log['memberId']    = $list;
					$log['cardId']      = $cardId;
					$log['money']       = $_REQUEST['payMoney'];
					$log['payTime']     = time();
					$log['payType']     = 0; //0:预存,1:消费,-1,退款
					$log['salerId']     = $_REQUEST['salerId'];
					$log['operatorId']  = $_SESSION[C('USER_AUTH_KEY')];//操作员id
					$log['remark']      = "开卡充值";
					$log['payNumber']      = $_REQUEST['payNumber'];
					$Paylog = M('Paylog');
					if($Paylog ->add($log)){
						$Member->commit(); //事务提交
						$this->assign ( 'jumpUrl', Cookie::get ( '_currentUrl_' ) );

						$this->success ('新增成功!');
					}
					return;
				}
			}
		}
		//失败提示
		$Member->rollback(); //事务回滚
		$this->error ('新增失败!');
	}

    //重置密码
    public function resetPwd()
    {
    	$id  =  $_POST['id'];
        $password = $_POST['password'];
        if(''== trim($password)) {
        	$this->error('密码不能为空！');
        }
        $Member = M('Member');
		$Member->password	=	md5($password);
		$Member->id			=	$id;
		$result	=	$Member->save();
        if(false !== $result) {
            $this->success("密码修改为$password");
        }else {
        	$this->error('重置密码失败！');
        }
    }

		/**
     +----------------------------------------------------------
	 * 根据表单生成查询条件
	 * 进行列表过滤
     +----------------------------------------------------------
	 * @access protected
     +----------------------------------------------------------
	 * @param string $name 数据对象名称
     +----------------------------------------------------------
	 * @return HashMap
     +----------------------------------------------------------
	 * @throws ThinkExecption
     +----------------------------------------------------------
	 */
	protected function _search($name = '') {
		//生成查询条件
		if (empty ( $name )) {
			$name = $this->getActionName();
		}
		$name=$this->getActionName();
		$model = D ( $name );
		$map = array ();
		foreach ( $model->getDbFields () as $key => $val ) {
			if (isset ( $_REQUEST [$val] ) && $_REQUEST [$val] != '') {
				if($val=='account'){
					$map ['dudu_member.account'] = $_REQUEST [$val];
					continue;
				}
				$map [$val] = $_REQUEST [$val];
			}
		}
		if(isset($_REQUEST ['cardNumber'])&& $_REQUEST ['cardNumber']!=''){
			$map ['cardNumber'] = $_REQUEST ['cardNumber'];
		}
		if(isset($_REQUEST ['cardSerial'])&& $_REQUEST ['cardSerial']!=''){
			$map ['cardSerial'] = $_REQUEST ['cardSerial'];
		}
		return $map;

	}

	/**
     +----------------------------------------------------------
	 * 根据表单生成查询条件
	 * 进行列表过滤
     +----------------------------------------------------------
	 * @access protected
     +----------------------------------------------------------
	 * @param Model $model 数据对象
	 * @param HashMap $map 过滤条件
	 * @param string $sortBy 排序
	 * @param boolean $asc 是否正序
     +----------------------------------------------------------
	 * @return void
     +----------------------------------------------------------
	 * @throws ThinkExecption
     +----------------------------------------------------------
	 */
	protected function _list($model, $map, $sortBy = '', $asc = false) {
		//排序字段 默认为主键名
		if (isset ( $_REQUEST ['_order'] )) {
			$order = $_REQUEST ['_order'];
		} else {
			$order = ! empty ( $sortBy ) ? $sortBy : $model->getPk ();
		}
		//排序方式默认按照倒序排列
		//接受 sost参数 0 表示倒序 非0都 表示正序
		if (isset ( $_REQUEST ['_sort'] )) {
			$sort = $_REQUEST ['_sort'] ? 'asc' : 'desc';
		} else {
			$sort = $asc ? 'asc' : 'desc';
		}
		//取得满足条件的记录数
		$count = $model
		          ->field('dudu_member.*,dudu_card.salerName,dudu_card.typeName,dudu_card.money,dudu_card.extMoney,dudu_card.startDate,dudu_card.endDate')
				  ->join("dudu_card on cardId=dudu_card.id")
		          ->where ( $map )->count ( 'dudu_member.id' );
		if ($count > 0) {
			import ( "@.ORG.Page" );
			//创建分页对象
			if (! empty ( $_REQUEST ['listRows'] )) {
				$listRows = $_REQUEST ['listRows'];
			} else {
				$listRows = '';
			}
			$p = new Page ( $count, C('PAGE_SIZE') );
			//分页查询数据
			$voList = $model
			          ->field('dudu_member.*,dudu_card.salerName,dudu_card.typeName,dudu_card.money,dudu_card.startDate,dudu_card.endDate')
					  ->join("dudu_card on cardId=dudu_card.id")
					  ->where($map)->order( "`" . $order . "` " . $sort)->limit($p->firstRow . ',' . $p->listRows)->findAll ( );
			//echo $model->getlastsql();
			//分页跳转的时候保证查询条件
			foreach ( $map as $key => $val ) {
				if (! is_array ( $val )) {
					$p->parameter .= "$key=" . urlencode ( $val ) . "&";
				}
			}
			//分页显示
			$page = $p->show ();
			//列表排序显示
			$sortImg = $sort; //排序图标
			$sortAlt = $sort == 'desc' ? '升序排列' : '倒序排列'; //排序提示
			$sort = $sort == 'desc' ? 1 : 0; //排序方式
			//模板赋值显示
			$this->assign ( 'list', $voList );
			$this->assign ( 'sort', $sort );
			$this->assign ( 'order', $order );
			$this->assign ( 'sortImg', $sortImg );
			$this->assign ( 'sortType', $sortAlt );
			$this->assign ( "page", $page );
		}
		Cookie::set ( '_currentUrl_', __SELF__ );
		return;
	}

 	public function index(){
    	//列表过滤器，生成查询Map对象
		$map = $this->_search ();
		if (method_exists ( $this, '_filter' )) {
			$this->_filter ( $map );
		}
		$name=$this->getActionName();
		$model = D ($name);
		if (! empty ( $model )) {
			$this->_list ( $model, $map );
		}
		$this->display ();
		return;
    }

	//查看会员信息
	public function showInfo(){
		//dump($_REQUEST);
		$Member   = M('Member');
		if(isset($_REQUEST['id'])){
			$mid      = $_REQUEST['id'];
			$member   = $Member->getById($mid);
		}
		if(isset($_REQUEST ['cardNumber'])&& $_REQUEST ['cardNumber']!=''){
			$member = $Member->field('dudu_member.*')->join("dudu_card on cardId=dudu_card.id")->where('cardNumber='.$_REQUEST ['cardNumber'])->find();
			$mid=$member['id'];
		}
		if(isset($_REQUEST ['cardSerial'])&& $_REQUEST ['cardSerial']!=''){
			$member = $Member->field('dudu_member.*')->join("dudu_card on cardId=dudu_card.id")->where('cardSerial='.$_REQUEST ['cardSerial'])->find();
			$mid=$member['id'];
			$this->assign('cardSerial',$_REQUEST ['cardSerial']);
		}
		if(isset($_REQUEST ['account'])&& $_REQUEST ['account']!=''){
			$member   = $Member->getByAccount($_REQUEST ['account']);
			$mid=$member['id'];
		}
		if(isset($_REQUEST ['trueName'])&& $_REQUEST ['trueName']!=''){
			$member   = $Member->where("trueName='{$_REQUEST[trueName]}'")->find();
			$mid=$member['id'];
		}
		if(isset($_REQUEST ['telephone'])&& $_REQUEST ['telephone']!=''){
			$member   = $Member->getByTelephone($_REQUEST ['telephone']);
			$mid=$member['id'];
		}

		$Inlog = M('Inlog'); //入场记录
		$where = array();
		$where['outTime'] =0;
		$where['memberId'] = $mid;
		$Y = date('Y',time());
		$m = date('m',time());
		$d = date('d',time());
		$today = strtotime("$Y-$m-$d");
		$where['_string'] = "inTime > $today";
		$inlog = $Inlog->where($where)->order('id desc')->find();
		$this     ->assign('inlog',$inlog);

		/*******************************************************
		 * 今日产品购买记录，前台显示为今日消费记录，显示用户今日的购买行为
		 *
		 * 修改时间：2011-07-29 20:49
		 *******************************************************
		 */
		$Paylog = M('Paylog');
		$paylog = $Paylog->where("cardId={$member['cardId']} AND payTime>$today")->order('payTime desc')->select();
		$this  -> assign('paylog', $paylog);
		// 今日产品购买记录 end

		
		$this     ->assign('member', $member);
		$Card     = M('Card');
		$card     = $Card->where('memberId='.$mid)->find();
		$this     ->assign('card', $card);
		$this     ->display();
	}

}
?>